<script lang="ts" setup>
import { MasonryInfiniteGrid } from '@egjs/vue3-infinitegrid';
import { articleApi } from '~/utils/api/article-api';

const column = ref(1);

function updateColumn() {
	switch (getScreenSize()) {
		case 'md':
			column.value = 1;
			return;
		case 'lg':
			column.value = 2;
			return;
		case 'xl':
			column.value = 3;
			return;
		case '2xl':
			column.value = 3;
			return;
		default:
			column.value = 1;
			return;
	}
}

onMounted(() => {
	updateColumn();
	window.addEventListener('resize', () => {
		updateColumn();
	});
});

const nextGroupKey = ref(1);
const pageNo = ref(1);

const items = ref(await getItems(pageNo.value, 10));

async function getItems(nextGroupKey: number, count: number) {
	const nextItems = await articleApi.getArticleList(pageNo.value, count);
	return nextItems.data.list.map(item => ({ ...item, key: item.article_id + '' + nextGroupKey, groupKey: nextGroupKey }));
}

function onRequestAppend(e) {
	nextGroupKey.value++;
	e.wait();
	e.currentTarget.appendPlaceholders(10, nextGroupKey);
	setTimeout(async () => {
		e.ready();
		const nextItems = await getItems(nextGroupKey.value, 10);
		if (items.value && nextItems)
			items.value = [...items.value, ...nextItems];
	}, 500);
}
</script>

<template>
	<div class="container py-[3.125rem]">
		<masonry-infinite-grid
			ref="masonryRef"
			:column="column"
			:gap="10"
			:observe-children="true"
			:use-resize-observer="true"
			class="relative w-full"
			@request-append="onRequestAppend"
		>
			<div
				v-for="(item, index) in items"
				:key="index"
				:data-grid-groupkey="item.groupKey"
				class="item w-full md:w-[50%] lg:w-[33%]"
			>
				<ArticleCard :article="item" />
			</div>
			<template #placeholder="{ item }">
				<div
					:key="item.key"
					:data-grid-groupkey="item.groupKey"
					class="placeholder w-full md:w-[50%] lg:w-[33%] h-[200px] bg-[#eee]"
				/>
			</template>
			<template #loading="{ item }">
				<div
					:key="item.key"
					:data-grid-groupkey="item.groupKey"
					class="loading"
				>
					加载中……
				</div>
			</template>
		</masonry-infinite-grid>
	</div>
</template>
